/**
 * Copyright 2010 - YangJiandong(chunquedong)
 * 
 * This file is part of ChunMap project
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
 * 
 * ChunMap是开源软件。你可以自由复制、传播本项目的下载包文件，但必须保持其完整性。
 * 我们不用对使用中的风险及由此造成的损失承担任何责任。
 * 详细情况请见《ChunMap许可协议》。
 * 
 * 想了解更多有关ChunMap的信息，请访问http://code.google.com/p/chunmap/
 * 
 * 下面此段程序作者YangJianDong(chunquedong)
 * 最后修改时间2010.7.17
 */
package chunmap.util.image;

import java.awt.Image;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;

import javax.imageio.ImageIO;

import chunmap.raster.ChunMapIOException;

public class ImageCache {
	public int cacheSize=200;
	private String path = "D:\\Temp\\chunmapData\\googlemap";
	public String format="png";

    private HashMap<String, Image> hash = new HashMap<String, Image>();
    private LinkedList<String> queue = new LinkedList<String>();

    public ImageCache(){
    	this.setBufferPath(path);
    }
    public void save(Image image, String name)
    {
    	File file;
		try {
			file = createFile(path , name + "."+format);
			ImageIO.write((RenderedImage)image,format,file);
    	
		} catch (IOException e) {
			e.printStackTrace();
			throw new ChunMapIOException();
		}
        cache(image, name);
    }
    
    private File createFile(String path, String name) throws IOException {
		File file = new File(path + File.separator + name);
		if (!file.exists()) {
			file.createNewFile();
		}
		return file;
	}

    private void cache(Image image, String name)
    {
        if (hash.size() >= cacheSize)
        {
            for (int i = 0; i < cacheSize/2; i++)
            {
                String key = queue.removeLast();
                hash.remove(key);
            }
        }
        hash.put(name, image);
        queue.addFirst(name);
    }

    public Image find(String name)
    {
        if (hash.containsKey(name))
        {
            return hash.get(name);
        }
        String imagepath = path + File.separator + name + "."+format;
        File file=new File(imagepath);
        if(!file.exists())return null;
		
        Image image;
		try {
			image = ImageIO.read(file);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		
        cache(image, name);
        return image;
    }

    public void setBufferPath(String path)
    {
    	File file = new File(path);
    	if(!file.exists()){
    		file.mkdir();
    	}
		this.path = path;
    }
}
